package edu.sctu.yueding.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Looper;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.LruCache;
import android.view.ViewGroup;
import android.widget.ImageView;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.LinkedList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * Created by 鑫爷您慢点 on 2016/8/3.
 */


public class ImageLoader {
    private static ImageLoader mInstance;

    /**
     * 图片的缓存核心
     */
    private LruCache<String, Bitmap> mLruCache;

    /**
     * 线程池
     */
    private ExecutorService mThreadPool;
    private static final int DEFAULT_THREAD_COUNT = 1;
    /**
     * 队列的调度方式
     */
    private Type mType = Type.LIFO;

    /**
     * 任务队列
     */
    private LinkedList<Runnable> mTaskQueue;

    /**
     * 后台轮询线程
     */
    private Thread mPoolThread;
    private android.os.Handler mPoolThreadHandler;
    /**
     * UI线程中的Handler
     */
    private android.os.Handler mUIHandler;

    private android.os.Handler mUIHandlerTwo;
    /**
     * 信号量机制
     */
    private Semaphore mSemaphorePoolThreadHandler = new Semaphore(0);

    private Semaphore mSemaphoreThreadPool;

    public enum Type {
        FIFO, LIFO,
    }

    private ImageLoader(int threadCount, Type type) {
        init(threadCount, type);
    }

    public static ImageLoader getInstance() {
        if (mInstance == null) {
            synchronized (ImageLoader.class) {
                if (mInstance == null) {
                    mInstance = new ImageLoader(DEFAULT_THREAD_COUNT, Type.LIFO);
                }
            }
        }
        return mInstance;
    }

    /**
     * @param type
     * @return
     */
    public static ImageLoader getInstance(int threadCount, Type type) {
        if (mInstance == null) {
            synchronized (ImageLoader.class) {
                if (mInstance == null) {
                    mInstance = new ImageLoader(threadCount, type);
                }
            }
        }
        return mInstance;
    }

    /**
     * 初始化操作
     *
     * @param threadCount
     * @param type
     */
    private void init(int threadCount, Type type) {
        //后台轮询线程
        mPoolThread = new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                mPoolThreadHandler = new android.os.Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        //线程池去取出一个任务去执行
                        mThreadPool.execute(getTask());

                        try {
                            mSemaphoreThreadPool.acquire();
                        } catch (InterruptedException e) {

                        }
                    }
                };
                //释放一个信号量
                mSemaphorePoolThreadHandler.release();
                Looper.loop();
            }
        };
        mPoolThread.start();

        //获取我们应用的最大可用内存
        int maxMemory = (int) Runtime.getRuntime().maxMemory();
        //设置缓存使用maxMemory/8
        int cacheMemory = maxMemory / 8;

        mLruCache = new LruCache<String, Bitmap>(cacheMemory) {
            @Override
            protected int sizeOf(String key, Bitmap value) {
                //测量每个Bitmap的值
                return value.getRowBytes() * value.getHeight();
            }
        };

        //创建线程池
        mThreadPool = Executors.newFixedThreadPool(threadCount);
        mTaskQueue = new LinkedList<Runnable>();
        mType = type;

        mSemaphoreThreadPool = new Semaphore(threadCount);
    }

    /**
     * 根据path为imageView设置图片（压缩后的bitmap）
     *
     * @param path
     * @param imageView
     */
    public void loadImage(final String path, final ImageView imageView, final boolean isURLPath) {

        imageView.setTag(path);//防止多次调用，imageView

        if (mUIHandler == null) {
            mUIHandler = new android.os.Handler() {
                @Override
                public void handleMessage(Message msg) {
                    //获取得到图片，为imageView回调设置图片
                    ImgBeanHolder holder = (ImgBeanHolder) msg.obj;
                    Bitmap bm = holder.bitmap;
                    String path = holder.path;
                    ImageView imageView = holder.imageView;
                    //将path与getTag存储路径进行比较
                    if (imageView.getTag().toString().equals(path)) {
                        imageView.setImageBitmap(bm);
                    }
                }
            };
        }
        //根据path获取缓存中的图片
        Bitmap bm = getBitmapFromLreCache(path);
        if (bm != null) {

            refreshBitmap(bm, path, imageView);

        } else {
            addTask(new Runnable() {
                @Override
                public void run() {
                    //加载图片
                    //图片的压缩
                    //1、获得图片需要显示的大小
                    ImageSize imageSize = getImageViewSize(imageView);
                    //2、压缩图片and加载图片
                    Bitmap bitmap = null;
                    /**
                     * 判断是否是获取网络图片
                     */
                    if (isURLPath) {
//                        bitmap = downloadImg(path, imageSize);
                        addBitmapToLruCache(path, bitmap);
                    } else {
                        bitmap = decodeSampledBitmapFromPath(imageSize.width, imageSize.height, path);
                        //3、把图片加入到缓存
                        addBitmapToLruCache(path, bitmap);
                    }

                    refreshBitmap(bitmap, path, imageView);

                    mSemaphoreThreadPool.release();
                }
            });
        }
    }


    /**
     * 根据path为imageView设置图片(原图)
     *
     * @param path
     * @param imageView
     */
    public void loadImageNoCondense(final String path, final ImageView imageView) {

        imageView.setTag(path);//防止多次调用，imageView

        if (mUIHandler == null) {
            mUIHandler = new android.os.Handler() {
                @Override
                public void handleMessage(Message msg) {
                    //获取得到图片，为imageView回调设置图片
                    ImgBeanHolder holder = (ImgBeanHolder) msg.obj;
                    Bitmap bm = holder.bitmap;
                    String path = holder.path;
                    ImageView imageView = holder.imageView;
                    //将path与getTag存储路径进行比较
                    if (imageView.getTag().toString().equals(path)) {
                        imageView.setImageBitmap(bm);
                    }
                }
            };
        }
        addTask(new Runnable() {
            @Override
            public void run() {
                //加载图片
                //图片的压缩
                //1、获得图片需要显示的大小
                ImageSize imageSize = getImageViewSize(imageView);
                //2、压缩图片and加载图片
                Bitmap bitmap = null;
                bitmap = decodeSampledBitmapFromPath(imageSize.width, imageSize.height, path);

                refreshBitmap(bitmap, path, imageView);

                mSemaphoreThreadPool.release();
            }
        });
    }

    private void refreshBitmap(Bitmap bm, String path, ImageView imageView) {
        Message message = Message.obtain();
        ImgBeanHolder holder = new ImgBeanHolder();

        holder.bitmap = bm;
        holder.path = path;
        holder.imageView = imageView;

        message.obj = holder;
        mUIHandler.sendMessage(message);
    }

    /**
     * 将图片加入到LruCache缓存中
     *
     * @param path
     * @param bm
     */
    private void addBitmapToLruCache(String path, Bitmap bm) {
        if (getBitmapFromLreCache(path) == null) {
            if (bm != null) {
                mLruCache.put(path, bm);
            }
        }
    }

    /**
     * 根据图片需要显示的宽和高进行压缩
     *
     * @param width
     * @param height
     * @param path
     * @return
     */
    private Bitmap decodeSampledBitmapFromPath(int width, int height, String path) {
        //
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;//获取图片的宽和高并不把图片加载到内存中
        BitmapFactory.decodeFile(path, options);
        options.inSampleSize = calculateInSampleSize(options, width, height);
        //使用获取的InSampleSize再次解析图片
        options.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeFile(path, options);
        return bitmap;
    }


    /**
     * 根据图片需要显示的宽和高进行压缩
     *
     * @param width
     * @param height
     * @param is
     * @return
     */
    private Bitmap decodeSampledBitmapFromInputStream(int width, int height, InputStream is) throws IOException {

        byte[] data = getBytes(is);//  解决  BitMap bitMap =  BitmapFactory.decodeStream(is,0,Options); 为null的bug
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;//获取图片的宽和高并不把图片加载到内存中
        BitmapFactory.decodeByteArray(data, 0, data.length, options);
        options.inSampleSize = calculateInSampleSize(options, width, height);
        //使用获取的InSampleSize再次解析图片
        options.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
        return bitmap;
    }


    /**
     * 将InputStream 转化为 byte[]
     *
     * @param is
     * @return
     * @throws IOException
     */
    public static byte[] getBytes(InputStream is) throws IOException {
        ByteArrayOutputStream outstream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024]; // 用数据装
        int len = -1;
        while ((len = is.read(buffer)) != -1) {
            outstream.write(buffer, 0, len);
        }
        outstream.close();
        // 关闭流一定要记得。
        return outstream.toByteArray();
    }

    /**
     * 根据需求的宽和高以及图片实际的宽和高计算SampleSize
     *
     * @param options
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        int width = options.outWidth;
        int height = options.outHeight;

        int inSampleSize = 1;

        if (width > reqWidth || height > reqHeight) {
            int widthRadio = Math.round(width * 1.0f / reqWidth);
            int heightRadio = Math.round(height * 1.0f / reqHeight);

            inSampleSize = Math.max(widthRadio, heightRadio);
        }
        return inSampleSize;
    }


    /**
     * 根据ImageView获取适当的宽和高
     *
     * @param imageView
     * @return
     */
    private ImageSize getImageViewSize(ImageView imageView) {
        ImageSize imageSize = new ImageSize();

        DisplayMetrics displayMetrics = imageView.getContext().getResources().getDisplayMetrics();
        ViewGroup.LayoutParams lp = imageView.getLayoutParams();

        int width = imageView.getWidth();//获取imageView的实际宽度
        if (width <= 0) {
            width = lp.width;//获取imageView在layout中声明的宽度
        }
        if (width <= 0) {
//            width = imageView.getMaxWidth();//检查最大值
            width = getImageViewFieldValue(imageView, "mMaxWidth");
        }
        if (width <= 0) {
            width = displayMetrics.widthPixels;//获取imageView在layout中声明的宽度
        }

        int height = imageView.getHeight();//获取imageView的实际高度
        if (height <= 0) {
            height = lp.height;//获取imageView在layout中声明的高度
        }
        if (height <= 0) {
//            height = imageView.getMaxHeight();//检查最大值
            height = getImageViewFieldValue(imageView, "mMaxHeight");
        }

        if (height <= 0) {
            height = displayMetrics.heightPixels;//获取imageView在layout中声明的宽度
        }

        imageSize.width = width;
        imageSize.height = height;

        return imageSize;
    }

    /**
     * 通过反射机制获取imageView的某个属性值
     *
     * @param object
     * @param fieldName
     * @return
     */
    private static int getImageViewFieldValue(Object object, String fieldName) {
        int value = 0;
        try {
            Field field = ImageView.class.getDeclaredField(fieldName);
            field.setAccessible(true);
            int fieldValue = field.getInt(object);
            if (fieldValue > 0 && fieldValue < Integer.MAX_VALUE) {
                value = fieldValue;
            }
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }


        return value;
    }

    private synchronized void addTask(Runnable runnable) {
        mTaskQueue.add(runnable);
        //if(mPoolThreadHandler == null)  wait();
        try {
            if (mPoolThreadHandler == null)
                mSemaphorePoolThreadHandler.acquire();
        } catch (InterruptedException e) {
        }
        ;
        mPoolThreadHandler.sendEmptyMessage(0x110);
    }

//    private Bitmap downloadImg(String url, ImageSize imageSize) {
//        String filePath;
//        Bitmap bitmap = null;
//        String appHome = Environment.getExternalStorageDirectory().getAbsolutePath() + "/爱咨询";
//        String name = DateFormat.format("yyyy-MM-dd-hh-mm-ss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
//
////        httpGet连接对象
//        HttpGet httpRequest = new HttpGet(url);
//        //取得HttpClient 对象
//        HttpClient httpclient = new DefaultHttpClient();
//        try {
//            //请求httpClient ，取得HttpRestponse
//            HttpResponse httpResponse = httpclient.execute(httpRequest);
//            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//                //取得相关信息 取得HttpEntiy
//                HttpEntity httpEntity = httpResponse.getEntity();
//                //获得一个输入流
//                InputStream is = httpEntity.getContent();
//
////                String filename = httpEntity.getContentEncoding().getValue();
////                Log.i("filename",filename);
//
//                bitmap = decodeSampledBitmapFromInputStream(imageSize.width, imageSize.height, is);
////                FileOutputStream outputStream = null;
////                File file = new File(appHome);
////                if (!file.exists()) {
////                    file.mkdirs();
////                }
////                filePath = file.getPath() + "/" + name;
////
////                outputStream = new FileOutputStream(new File(filePath));
////                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
////
////                outputStream.flush();
////                outputStream.close();
//                is.close();
//            }
//
//        } catch (ClientProtocolException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        } catch (IOException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//        return bitmap;
//
//    }

    /**
     * 根据path获取缓存中的图片
     *
     * @param path
     * @return
     */
    private Bitmap getBitmapFromLreCache(String path) {
        return mLruCache.get(path);
    }

    /**
     * 从任务队列取出一个方法
     *
     * @return
     */
    private Runnable getTask() {
        if (mType == Type.FIFO) {
            return mTaskQueue.removeFirst();
        } else if (mType == Type.LIFO) {
            return mTaskQueue.removeLast();
        }
        return null;
    }

    private class ImageSize {
        int width;
        int height;
    }

    private class ImgBeanHolder {
        Bitmap bitmap;
        ImageView imageView;
        String path;
    }

}